<template>
  <div class="page">
    <el-form :model="searchForm" label-position="left" inline label-suffix="：" size="small">
      <div class="flex wap flex-start">
        <el-form-item label="名称">
          <el-input v-model="searchForm.name" maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" maxlength="11" clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="getData">查询</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="flex wap flex-between" style="padding: 0px 0 10px 0;width:100%">
      <div>
        <el-button type="success" @click="addData">新增</el-button>
        <div style="width:20px"></div>
      </div>
      <div class="flex">
        <el-button type="primary" @click="downLoadStu" plain>导出学生</el-button>
        <div style="width:20px"></div>
        <import-file @uploadUrl="uploadUrl">
          <el-button type="success" plain>批量导入学生</el-button>
        </import-file>
        <div style="width:20px"></div>
        <el-button type="warning" @click="addMoBan" plain>导入模板下载</el-button>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"  height="600"  :header-cell-style="{
        background: '#eef1f6',
        color: '#606266',
        'text-align': 'center'
      }"
      :cell-style="{ 'text-align': 'center' }">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="name" label="卡号">
        <template slot-scope="scop">
          <el-tag size="mini" v-if="scop.row.stucardnum" @click="setCard(scop.row)">{{scop.row.stucardnum}}</el-tag>
          <el-tag size="mini" type="warning" v-else @click="setCard(scop.row)">设置学生卡</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="phone" label="家长手机号"></el-table-column>
      <el-table-column prop="sex" label="性别"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="idcard" label="身份证号"></el-table-column>
      <el-table-column prop="address" label="住址"></el-table-column>
      <el-table-column prop="createtime" label="创建时间"></el-table-column>
      <el-table-column prop="" label="操作" width="120">
        <template slot-scope="scop">
          <el-button type="primary" icon="el-icon-edit" circle @click="edit(scop.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="del(scop.row.stuid)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="float:right;padding:10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="设置卡号" center :visible.sync="setPop" width="40%">
      <el-form :model="setNum" ref="setStuForm" :rules="setStu" label-width="110px" class="edit-form" label-suffix="：">
        <el-form-item label="学生卡" prop="stucardnum">
          <el-input type="text" placeholder="请输入卡号或刷卡" v-model="setNum.stucardnum" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setPop = false">取 消</el-button>
        <el-button type="primary" @click="setNumSave">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="学员信息" center :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="addOrUpdateForm" ref="addSetForm" :rules="addrule" label-width="110px" class="edit-form"
        label-suffix="：">
        <el-form-item label="姓名" prop="name">
          <el-input type="text" placeholder="请输入姓名" v-model="addOrUpdateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input type="text" placeholder="请输入昵称" v-model="addOrUpdateForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addOrUpdateForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="text" placeholder="请输入年龄" v-model="addOrUpdateForm.age"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idcard">
          <el-input type="text" placeholder="请输入身份证号" v-model="addOrUpdateForm.idcard"></el-input>
        </el-form-item>
        <el-form-item label="家长手机号" prop="phone">
          <el-input type="text" placeholder="请输入家长手机号" maxlength="11" v-model="addOrUpdateForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input type="text" placeholder="请输入住址" v-model="addOrUpdateForm.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSave" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { findStudents, updateStuCardNum, addStudent, updateStudent, delStudent, importStudentMuban, importStudent, exportStudent } from "@/api/user";
export default {
  data() {
    return {
      total: 0,
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      saveLoading: false,
      dialogFormVisible: false,
      selectionList: [],
      setPop: false,
      setStuNum: '',
      searchForm: {
        name: "",
        phone: ""
      },
      setNum: {
        stucardnum: '',
      },
      opId: '',
      addOrUpdateForm: {
        stuid: '',
        name: '',
        nickname: '',
        sex: '',
        age: '',
        idcard: '',
        phone: '',
        address: ''
      },
      setStu: {
        stucardnum: [
          { required: true, message: '卡号不能为空', trigger: 'change' },
          { pattern: this.$reg.reg_number, message: '卡号必须为数字', trigger: 'change' }
        ]
      },
      addrule: {
        name: [
          { required: true, message: '必须填写姓名', trigger: 'change' }
        ],
        age: [
          { required: true, message: '必须填写年龄', trigger: 'change' },
          { pattern: this.$reg.reg_number, message: '年龄必须为正整数', trigger: 'change' },
        ],
        phone: [
          { required: true, message: '必须填写家长手机号', trigger: 'change' },
          { pattern: this.$reg.reg_phone, message: '手机号格式错误', trigger: 'change' },
        ],
        idcard: [
          { pattern: this.$reg.reg_idcard, message: '身份证号格式错误', trigger: 'change' },
        ]
      }

    };
  },
  computed: {
    queryData() {
      const { name, phone } = this.searchForm
      return {
        name,
        phone,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData() {
      const res = await findStudents.post(this.queryData);
      if (res.resultCode === "000000") {
        this.tableData = res.data.studentList;
        this.total = res.data.count;
      } else {
        this.$message.error(res.resultInfo);
      }
    },
    setCard(val) {
      this.setPop = true
      this.opId = val.stuid
      this.setNum.stucardnum = val.stucardnum
    },
    setNumSave() {
      this.$refs.setStuForm.validate(async (valid) => {
        if (valid) {
          const res = await updateStuCardNum.post({ stuid: this.opId, stucardnum: this.setNum.stucardnum })
          console.log(res, 111);
          
          if (res.resultCode === "000000") {
            this.$message.success(res.resultInfo);
            this.setPop = false
            this.getData()
          } else {
            this.$message.error(res.resultInfo);
          }
        }
      })
    },
    addData() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['addSetForm'].resetFields();
      })
      this.addOrUpdateForm = {
        stuid: '',
        name: '',
        nickname: '',
        sex: '',
        age: '',
        idcard: '',
        phone: '',
        address: ''
      }
    },
    edit(row) {
      this.dialogFormVisible = true
      const { stuid, name, nickname, sex, age, idcard, phone, address } = row
      this.addOrUpdateForm = {
        stuid,
        name,
        nickname,
        sex,
        age,
        idcard,
        phone,
        address
      }
    },
    addSave() {
      this.$refs.addSetForm.validate(async (valid) => {
        if (valid) {
          this.saveLoading = true
          const res = this.addOrUpdateForm.stuid ? await updateStudent.post(this.addOrUpdateForm) : await addStudent.post(this.addOrUpdateForm);
          this.saveLoading = false
          if (res.resultCode === "000000") {
            this.$message.success(res.resultInfo);
            this.dialogFormVisible = false
            this.getData()
          } else {
            this.$message.error(res.resultInfo);
          }
        } else {
          return false;
        }
      });
    },
    downLoadStu() {
      if (this.selectionList.length > 0) {
        this.$confirm("此操作将导出【" + this.selectionList.length + "】条数据, 是否继续?", "提示", {
          confirmButtonText: "确认导出",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const ids = this.selectionList.map(e => e.stuid)
          this.exportStu({ stuids: ids })
        })
      } else {
        this.$confirm("此操作将导出全部数据, 是否继续?", "提示", {
          confirmButtonText: "确认导出",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportStu(this.queryData)
        })
      }
    },
    async exportStu(ids) {
      const res = await exportStudent.post(ids);
      if (res.resultCode === "000000") {
        this.$message.success(res.resultInfo);
        this.$download(res.data, this.$Url + '/uploadtemp/' + res.data)
        this.getData()
      } else {
        this.$message.error(res.resultInfo);
      }
    },
    handleSelectionChange(val) {
      this.selectionList = val
    },
    async addMoBan() {
      const res = await importStudentMuban.post();
      if (res.resultCode === "000000") {
        this.$message.success(res.resultInfo);
        this.$download(res.data, this.$Url + '/uploadtemp/' + res.data)
      } else {
        this.$message.error(res.resultInfo);
      }

      // this.$message.success('正在下载...');
      // this.$downloadBlob('学生导入模板.xls', res.data)
      // if (res.fileName) {
      //   const fname = res.fileName.filter(e => e.includes('filename'))
      //   const name = fname.length ? fname[0].split('=')[1] : '上传结果.xls'
      //   this.$message.success('正在下载上传结果...');
      //   this.$downloadBlob(name, res.data)
      // }else{
      //   this.$message.error('下载失败，请重试');
      // }
    },
    async uploadUrl(url) {
      const res = await importStudent.post({ 'importUrl': url });
      if (res.resultCode === "000000") {
        this.$message.success(res.resultInfo);
        this.$download(res.data, this.$Url + '/uploadtemp/' + res.data)
        this.getData()
      } else {
        this.$message.error(res.resultInfo);
      }
    },
    del(id) {
      this.$confirm("此操作将删除该项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.delItem(id)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async delItem(id) {
      const res = await delStudent.post({ stuid: id });
      if (res.resultCode === "000000") {
        this.$message.success(res.resultInfo);
        this.getData()
      } else {
        this.$message.error(res.resultInfo);
      }
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getData();
    }
  }
};
</script>
<style lang="less" scoped></style>
